#include "eventloop/Eventloop.h"
//#include <muduo/net/EventLoopThread.h>
#include "thread/Thread.h"
#include "utility/chrono.h"
#include "timer/TimerID.h"
#include <functional>
#include <stdio.h>
#include <unistd.h>
#include <iostream>


int cnt = 0;
Eventloop* g_loop;
Utility::timepoint now;

void printTid()
{
  printf("pid = %d, tid = %d\n", getpid(), CurrentThread::tid());
  printf("now %s \n", Utility::to_string(Utility::now()).c_str());
}

void print(const char* msg)
{
  Utility::timepoint now2 =  Utility::now();
  Utility::duration delta = now2 - now;

  printf("%.1f : msg %s %s\n",  Utility::cast_second(delta), Utility::to_string(Utility::now()).c_str(), msg);
  if (++cnt == 20)
  {
    g_loop->quit();
  }
}

void cancel(TimerID timer)
{
  Utility::timepoint now2 =  Utility::now();
  Utility::duration delta = now2 - now;
  g_loop->cancel(timer);
  printf("%.1f : cancelled at %s\n", Utility::cast_second(delta), Utility::to_string(Utility::now()).c_str());
}

int main()
{
  printTid();
  sleep(1);
  {
    Eventloop loop;
    g_loop = &loop;

    print("main");
    now =  Utility::now();
    loop.run_after(1, std::bind(print, "once1"));
    loop.run_after(1.5, std::bind(print, "once1.5"));
    loop.run_after(2.5, std::bind(print, "once2.5"));
    loop.run_after(3.5, std::bind(print, "once3.5"));
    TimerID t45 = loop.run_after(4.5, std::bind(print, "once4.5"));
    loop.run_after(4.2, std::bind(cancel, t45));
    loop.run_after(4.8, std::bind(cancel, t45));
    loop.run_every(2, std::bind(print, "every2"));
    TimerID t3 = loop.run_every(3, std::bind(print, "every3"));
    loop.run_after(9.5, std::bind(cancel, t3));

    loop.loop();
    print("main loop exits");
  }
  /*
  sleep(1);
  {
    EventLoopThread loopThread;
    EventLoop* loop = loopThread.startLoop();
    loop->run_after(2, printTid);
    sleep(3);
    print("thread loop exits");
  }
  */
}
